package com.acme.bankapp.service;

import java.io.*;
import java.net.*;

import com.acme.bankapp.domain.*;
import com.acme.bankapp.service.*;

public class BankServer {
	ServerSocket ss;
	Socket clientSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;

	public void startServer(Bank bank) {
		try {
			ss = new ServerSocket(5050);
			System.out.println("Waiting for connection...");
			clientSocket = ss.accept();
			System.out.println("Connection received from "
					+ clientSocket.getInetAddress().getHostName());
			out = new ObjectOutputStream(clientSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(clientSocket.getInputStream());
			do {
				try {
					message = (String) in.readObject();
					System.out.println("client>" + message);
					if (message.equals("addClient")) {
						sendMessage("InputFile: ");
						BankDataLoaderService.load(bank,
								(String) in.readObject());
						sendMessage("Data loaded");
					}
				} catch (ClassNotFoundException classnot) {
					System.err.println("Data received in unknown format");
				}
			} while (!message.equals("exit"));
		} catch (UnknownHostException unknownHost) {
			System.err.println("You are trying to connect to an unknown host!");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				ss.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}

	}

	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println("server>" + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

}
